<template>
  <el-dialog
    title="设备配置计划"
    :visible.sync="show"
    width="1000px"
    center
    :close-on-click-modal="false"
  >
    <el-form
      ref="form"
      :rules="rules"
      style="padding-top: 10px"
      :model="form"
      label-width="100px"
    >
      <div class="com-form-title">基础信息</div>
      <el-row>
        <!-- <el-col :span="12">
          <el-form-item label="申请编号" prop="applyNumber">
            <el-input v-model="form.applyNumber" :disabled="disableForm" />
          </el-form-item>
        </el-col> -->
        <el-col :span="8">
          <el-form-item label="申请时间" prop="applyTime">
            <el-date-picker
              v-model="form.applyTime"
              style="width: 100%"
              type="date"
              :disabled="disableForm"
            />
          </el-form-item>
        </el-col>
        <!-- <el-col :span="8">
          <el-form-item label="编制人单位" prop="founderUnit">
            <el-input v-model="form.founderUnit" :disabled="disableForm" />
          </el-form-item>
        </el-col> -->
        <el-col :span="8">
          <el-form-item label="计划总金额" prop="amount">
            <el-input v-model="form.amount" :disabled="disableForm" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" :disabled="disableForm" />
          </el-form-item>
        </el-col>
      </el-row>

      <div style="padding-bottom: 10px">
        <el-button
          type="primary"
          @click="showTargetSetListModal = true"
        >引入设备</el-button>
      </div>
      <com-table
        v-model="selectRow"
        highlight-current-row
        :data="targetList"
        :columns="columns"
        :no-page="true"
      >
        <template v-slot:unit="{ row }">
          <!-- <el-input v-model="row.unit" /> -->
          <el-select
            v-model="row.unit"
            :disabled="disableForm"
            style="width: 100%"
            placeholder="请选择"
          >
            <el-option label="台班" value="1" />
            <el-option label="小时" value="2" />
            <el-option label="月" value="3" />
            <el-option label="吨" value="4" />
            <el-option label="㎡" value="5" />
            <el-option label="m³" value="6" />
          </el-select>
        </template>
        <template v-slot:workload="{ row }">
          <el-input v-model="row.workload" />
        </template>
        <template v-slot:specification="{ row }">
          <el-input v-model="row.specification" />
        </template>
        <template v-slot:unitPrice="{ row }">
          <el-input v-model="row.unitPrice" />
        </template>
        <template v-slot:sumPrice="{ row }">
          <el-input v-model="row.sumPrice" @focus="sum()" />
        </template>
        <template v-slot:useUnit="{ row }">
          <el-input v-model="row.useUnit" />
        </template>
        <template v-slot:approachLocation="{ row }">
          <el-input v-model="row.approachLocation" />
        </template>
        <template v-slot:approachTime="{ row }">
          <!-- <el-input v-model="row.approachTime" /> -->
          <el-date-picker
            v-model="row.approachTime"
            type="date"
            placeholder="选择日期"
          />
        </template>
        <template v-slot:remark="{ row }">
          <el-input v-model="row.remark" />
        </template>
        <template v-slot:options="{ row }">
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="deleteTarget(row)"
          >删除</el-button>
        </template>
      </com-table>
      <el-button
        style="margin-top: 10px"
        type="primary"
        @click="showFileModal = true"
      >附件资料({{ fileList.length }})</el-button>
      <file-uploader
        v-model="fileList"
        :show-modal.sync="showFileModal"
        :disabled="disableForm"
        :can-download="optType === 'detail'"
      />
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="show = false">取 消</el-button>
      <el-button type="primary" @click="saveDoc">确 定</el-button>
    </span>
    <tree-modal
      title="机械设备选择(多选)"
      :show-modal.sync="showTargetSetListModal"
      :columns="columns"
      :check-lock="true"
      :api-obj="{
        tree: getMachineDirectoryTree,
        list: getMachineDeviceDetailList,
      }"
      @getSelectedRows="getSelectedRows"
    />

    <!-- <only-tree-modal title="机械选择" :show-modal.sync="showTargetSetListModal" :columns="columns" :api-obj="{tree:getMachineDirectoryTree}" @getSelectedRows="getSelectedRows" /> -->
  </el-dialog>
</template>

<script>
import {
  addDeviceConfigPlanInfo,
  updateDeviceConfigPlanInfo,
  getDeviceConfigPlanInfoDetail
} from '@/api/consumableManage'
import { getAreaList } from '@/api/common'
import { workflowStatus } from '@/utils/dicData'
import fileUploader from '@/components/FileUploader'
import {
  getMachineDirectoryTree,
  getMachineDeviceDetailList
} from '@/api/basicCode'

// import deviceList from './deviceList'
import treeModal from './machineSelect.vue'
// import onlyTreeModal from '@/components/TreeModal/onlytree'
export default {
  name: 'AddDeviceConfigPlanInfo',
  components: {
    fileUploader,
    treeModal
    // deviceList
    // onlyTreeModal
  },
  props: {
    showModal: {
      type: Boolean,
      default: false
    },
    optType: {
      type: String,
      default: 'add'
    },
    dir: {
      type: Object,
      default() {
        return {}
      }
    },
    data: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
    return {
      getMachineDirectoryTree,
      getMachineDeviceDetailList,
      showFileModal: false,
      selectRow: null,
      targetList: [],
      workflowStatus,

      addType: '', // same   under
      visible: false,
      showAdd: false,
      selectedNode: null,
      form: {
        // applyNumber: '',
        applyTime: '',
        amount: '',
        remark: ''
        // addWorkflowId: '',
        // status: '',
        // founderName: '',
        // createTime: '',
        // founderUnit: ''
      },
      columns: [
        {
          label: '设备名称',
          prop: 'name',
          width: '180'
        },
        {
          label: '设备编号',
          prop: 'number'
        },
        {
          label: '规格',
          prop: 'specification',
          slot: 'specification'
        },
        {
          label: '单位',
          prop: 'unit',
          slot: 'unit',
          width: '110'
        },
        {
          label: '预估工作量',
          prop: 'workload',
          slot: 'workload',
          width: '100'
        },
        {
          label: '单价',
          prop: 'unitPrice',
          slot: 'unitPrice',
          width: '100'
        },
        {
          label: '合价',
          prop: 'sumPrice',
          slot: 'sumPrice',
          width: '100'
        },
        {
          label: '使用单位',
          prop: 'useUnit',
          slot: 'useUnit',
          width: '150'
        },
        {
          label: '进场地点',
          prop: 'approachLocation',
          slot: 'approachLocation',
          width: '200'
        },
        {
          label: '进场时间',
          prop: 'approachTime',
          slot: 'approachTime',
          width: '140'
        },
        {
          label: '备注',
          prop: 'remark',
          slot: 'remark'
        },
        {
          fixed: 'right',
          label: '操作',
          width: '140',
          prop: 'options',
          slot: 'options'
        }
      ],
      showTargetSetListModal: false,
      fileList: [],
      rules: {
        applyTime: [
          { required: true, message: '请选择申请时间', trigger: 'change' }
        ],
        remark: [
          { required: true, message: '请选择备注', trigger: 'change' }
        ],
        unifiedSocialCreditCode: [
          { required: true, message: '统一社会信用代码', trigger: 'change' }
        ]
      },
      provinceData: [],
      cityData: []
    }
  },
  computed: {
    disableForm() {
      return this.optType === 'detail'
    },
    show: {
      get() {
        return this.showModal
      },
      set(val) {
        this.$emit('update:showModal', val)
      }
    }
  },
  watch: {
    showModal(val) {
      if (val) {
        this.getDocDetail(this.data.id)
        if (this.optType !== 'add') {
          Object.keys(this.form).forEach((key) => {
            const source = this.data[key]
            if (typeof source === 'boolean') {
              this.form[key] = source ? 1 : 0
            } else {
              this.form[key] = source
            }
          })
        }
      } else if (!val) {
        this.fileList = []
        this.targetList = []
        this.$refs.form.resetFields()
      }
    }
  },
  mounted() {
    this.getRegionData()
  },
  methods: {
    sum() {
      this.form.amount = 0
      this.targetList.forEach((item) => {
        item.sumPrice = item.unitPrice * item.workload
        this.form.amount = this.form.amount + item.sumPrice * 1
      })
      this.$forceUpdate()
    },
    deleteTarget(obj) {
      this.targetList.map((item, m) => {
        if (item.code === obj.code) {
          this.targetList.splice(m, 1)
        }
      })
    },
    getSelectedRows(data) {
      // this.targetList = this.targetList.concat(data.map(item => {
      //   return {
      //     ...item
      //   }
      // }))
      this.targetList = this.targetList.concat(
        data.map((item) => {
          return {
            name: item.devName,
            number: item.devNumber,
            specification: item.specification,
            unit: '',
            workload: '',
            unitPrice: '',
            sumPrice: '',
            useUnit: '',
            approachLocation: '',
            approachTime: ''
          }
        })
      )
    },
    provinceChange(e) {
      const selectedData = this.provinceData.filter((val) => val.name === e)[0]
      if (selectedData) {
        this.form.city = ''
        const params = {
          parentCode: selectedData.code,
          areaType: 2
        }
        getAreaList(params).then((res) => {
          this.cityData = res.data || []
        })
      }
    },
    getDocDetail(id) {
      getDeviceConfigPlanInfoDetail({ deviceConfigPlanInfoId: id }).then(
        (res) => {
          const { lstAttachment, lstDeviceConfigPlanDetail } = res.data || {}
          if (lstAttachment && lstAttachment.length > 0) {
            this.fileList = lstAttachment
          }
          if (
            lstDeviceConfigPlanDetail &&
            lstDeviceConfigPlanDetail.length > 0
          ) {
            this.targetList = lstDeviceConfigPlanDetail.map(item => {
              return {
                ...item,
                unit: item.unit.toString()
              }
            })
          }
        }
      )
    },
    getRegionData() {
      getAreaList({ areaType: '1' }).then((res) => {
        this.provinceData = res.data || []
      })
    },
    deleteDetail() {},
    saveDoc() {
      if (this.optType === 'detai') {
        this.show = false
        return
      }
      this.$refs.form.validate((valid) => {
        if (valid) {
          // this.targetList.map(item => {
          //   item.id = ''
          // })
          const params = {
            deviceConfigPlanInfo: {
              ...this.form,
              ...(this.optType === 'edit'
                ? {
                  id: this.data.id
                }
                : {})
            },
            lstAttachment: this.fileList,
            lstDeviceConfigPlanDetail: this.targetList.map((item) => {
              return {
                ...item,
                ...(this.optType === 'edit'
                  ? {
                    deviceConfigPlanInfoId: this.data.id
                  }
                  : {})
              }
            })
          }
          const fn =
            this.optType === 'add'
              ? addDeviceConfigPlanInfo
              : updateDeviceConfigPlanInfo
          fn(params).then((res) => {
            if (res.code === '0001') {
              this.$message({
                type: 'success',
                message: '保存成功!'
              })
              this.show = false
              this.$emit('freshList')
              this.$refs.form.resetFields()
            } else {
              this.$message({
                type: 'error',
                message: res.msg
              })
            }
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.com-form-title {
  font-size: 14px;
  font-weight: bold;
  line-height: 35px;
  color: #409eff;
  border-bottom: 1px solid #dedede;
  margin-bottom: 6px;
}
</style>
